﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.APIRequestModels.SysUser;
using Ekton_Manage_DTO.RequestModels.Auth;
using Ekton_Manage_DTO.RequestModels.SysUser;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Ekton_Manage_Web.Controllers
{
    /// <summary>
    /// 前端用户登录，注册，忘记密码
    /// </summary>
    /// 
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApiLoginController : ControllerBase
    {
        private readonly IUserBusiness _userBusiness;
        private readonly IBaseRepository<user_list, int> _repository;
        private readonly IApiUserLogin _apiUserLogin;
        private readonly IConfiguration _configuration;
        private readonly CommonHelper _commonHelper;
        public ApiLoginController(IBaseRepository<user_list, int> repository, IApiUserLogin apiUserLogin, IUserBusiness userBusiness, IConfiguration configuration, CommonHelper commonHelper)
        {
            _repository = repository;
            _apiUserLogin = apiUserLogin;
            _userBusiness = userBusiness;
            _configuration = configuration;
            _commonHelper = commonHelper;

        }

        /// <summary>
        /// 前端用户登录
        /// </summary>
        /// <param name="parame"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetToken([FromBody] CheckIdentity parame)
        {
            #region 登录验证
            dynamic userData = await _userBusiness.APICheckLogin(parame.loginName, parame.password);
            var userInfo = await _repository.QuerySingleData(m => m.account == parame.loginName);
            if (userInfo is null)
            {
                return Ok(new { msg = "没有该用户!", token = default(string), code = 400, });

            }
            else
            {
                if (userInfo.state == 2)
                {
                    return Ok(new { msg = "该用户已被停用!", code = 202, });
                }
            }
            if (userData is null) return Ok(new { msg = "用户名或密码错误!", token = default(string), code = 400, });
            #endregion
            #region JWT-Token
            Const.ValidAudience = parame.loginName + parame.password + DateTime.Now.ToString();
            var claims = new[]
            {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.NameIdentifier, JsonConvert.SerializeObject(new{ id=userData.id,name=parame.loginName,platform="not-backstage"}))
                };
            //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            var token = new JwtSecurityToken(
               issuer: Const.Domain, //颁发者
               audience: "Ekton-Client",
               expires: DateTime.Now.AddDays(7),// 过期时间
               signingCredentials: creds, //签名证书
               claims: claims);//自定义参数
            #endregion
            return Ok(new
            {
                msg = "登陆成功!",
                token = new JwtSecurityTokenHandler().WriteToken(token),
                code = 200,
                success = true,
                uid = userData.id,
                userName = parame.loginName,
                token_type = "Bearer",
                expires_in = await _commonHelper.ConvertDateTimeToInt(DateTime.Now.AddMinutes(30))
            });
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Message> ApiPostUserRegsiter([FromBody] ApiDtoInsertUserRegister rquest)
        {
            return await _apiUserLogin.ApiPostUserRegsiter(rquest);
        }

        /// <summary>
        /// 忘记密码
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Message> ApiPostUserPass([FromBody] ApiDtoInsertUserPass request)
        {
            return await _apiUserLogin.ApiPostUserPass(request);

        }
    }
}
